package com.lancoo.znbkxx.teacher.diagnosis

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Rect
import android.graphics.Typeface
import android.view.View
import android.widget.SeekBar
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.ViewModelProvider
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseFragment
import com.lancoo.znbkxx.teacher.model.data.MonthTime
import com.lancoo.znbkxx.teacher.net.BkApiMethods
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import kotlinx.android.synthetic.main.fragment_plates.*
import kotlinx.android.synthetic.main.item_achievement_markview.view.*
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.*
import java.util.concurrent.TimeoutException

/**
 * @author : Admin
 * @date   : 2020/12/16
 * @desc   :
 */
class PlatesFragment : BaseFragment() {
    private val barEntriesMonth = mutableListOf<BarEntry>()
    private val barEntriesWeek1st = mutableListOf<BarEntry>()
    private val barEntriesWeek2nd = mutableListOf<BarEntry>()
    private val barEntriesWeek3rd = mutableListOf<BarEntry>()
    private val barEntriesWeek4th = mutableListOf<BarEntry>()
    private val xLabels = mutableListOf<String>()
    private val zsdArea by lazy { arguments?.getString("zsdarea") }
    private lateinit var viewModel: PaperViewModel
    override fun createLayout(): Int {
        return R.layout.fragment_plates
    }

    override fun initView(view: View?) {
        viewModel = ViewModelProvider(requireActivity()).get(PaperViewModel::class.java)
        lifecycle.addObserver(viewModel)
        btn_plates.setOnClickListener {
            val intent = Intent(requireContext(), SelfPlatesActivity::class.java)
            intent.putExtra("zsdarea", zsdArea)
            intent.putExtra("stuID", viewModel.StuID.value)
            startActivity(intent)
        }
        getStuCognitiveIndex()
    }

    @SuppressLint("CheckResult")
    private fun getStuCognitiveIndex() {
        val method = BkApiMethods(requireContext())
        val params = BkApiMethods.Paramas()
        params["ZsdArea"] = zsdArea
        params["StuID"] = viewModel.StuID.value
        method.getStuCognitiveIndex(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                val currentMonthValue = "${Calendar.getInstance().get(Calendar.MONTH) + 1}月"
                var monthValue = 0
                it.Data.MonthTimeList.forEach { monthTime ->
                    if (currentMonthValue == monthTime.MonthName) {
                        monthValue = monthTime.MonthValue
                    }
                }
                tv_change_num.typeface = Typeface.createFromAsset(activity?.assets,
                        "fonts/cool_black.TTF")
                tv_change_num.text = HtmlUtils.setText(
                        "<font color='#00afff'>${monthValue}</font><font color='#35bb29'>（月增长${it.Data.MonthAdd}分）</font>")
                initRank()
                ObjectAnimator.ofInt(seekBar, "secondaryProgress", 0,
                        ((monthValue - it.Data.MonthAdd) / 100))
                        .apply {
                            duration = 800
                            startDelay = 500L
                            start()
                        }
                ObjectAnimator.ofInt(seekBar, "progress", 0, (monthValue / 100))
                        .apply {
                            duration = 800
                            startDelay = 500L
                            start()
                        }
                initBarChart(it.Data.MonthTimeList)
            } else {
                MyToast.showToast(it.Message)
            }
        }, {
            val error: String = if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                getString(R.string.aibk_network_timeout)
            } else {
                getString(R.string.aibk_server_sick)
            }
            MyToast.showToast( error)
        })
    }

    private fun initRank() {
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                setSeekCurTimeLocation(progress)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }

        })
        seekBar.isEnabled = false
    }

    private fun setSeekCurTimeLocation(progress: Int) {
        if (tv_change_num == null) {
            return
        }
        val layoutParams = tv_change_num.layoutParams as ConstraintLayout.LayoutParams
        val marginStart = (progress * 0.94f * seekBar.width.toFloat() / 100f).toInt()
        if (marginStart + tv_change_num.width > seekBar.width + DensityUtils.dp2px(requireContext(),
                        26f)) {
            layoutParams.marginStart = seekBar.width - (tv_change_num.width - DensityUtils.dp2px(
                    requireContext(), 30f))
        } else {
            layoutParams.marginStart = marginStart
        }
        tv_change_num.layoutParams = layoutParams
    }

    private fun initBarChart(data: List<MonthTime>) {
        barEntriesMonth.clear()
        barEntriesWeek1st.clear()
        barEntriesWeek2nd.clear()
        barEntriesWeek3rd.clear()
        barEntriesWeek4th.clear()
        xLabels.clear()
        val groupSpace = 0.6f
        val barSpace = 0.02f
        val barWidth = 0.06f
        val drawable = ResourcesCompat.getDrawable(resources, R.mipmap.aibk_icon_zero, null)
                ?.apply {
                    bounds = Rect(0, 0, 11, 16)
                }
        data.forEachIndexed { index, monthTime ->
            val barEntryMonth = BarEntry(index.toFloat() + 0.5f, monthTime.MonthValue.toFloat())
            if (monthTime.MonthValue == 0) {
                barEntryMonth.icon = drawable
            }
            val barEntryWeek1st = BarEntry(index.toFloat() + 0.5f,
                    monthTime.WeekTimeList[0].WeekValue.toFloat())
            if (monthTime.WeekTimeList[0].WeekValue == 0) {
                barEntryWeek1st.icon = drawable
            }
            val barEntryWeek2nd = BarEntry(index.toFloat() + 0.5f,
                    monthTime.WeekTimeList[1].WeekValue.toFloat())
            if (monthTime.WeekTimeList[1].WeekValue == 0) {
                barEntryWeek2nd.icon = drawable
            }
            val barEntryWeek3rd = BarEntry(index.toFloat() + 0.5f,
                    monthTime.WeekTimeList[2].WeekValue.toFloat())
            if (monthTime.WeekTimeList[2].WeekValue == 0) {
                barEntryWeek3rd.icon = drawable
            }
            val barEntryWeek4th = BarEntry(index.toFloat() + 0.5f,
                    monthTime.WeekTimeList[3].WeekValue.toFloat())
            if (monthTime.WeekTimeList[3].WeekValue == 0) {
                barEntryWeek4th.icon = drawable
            }
            barEntriesMonth.add(barEntryMonth)
            barEntriesWeek1st.add(barEntryWeek1st)
            barEntriesWeek2nd.add(barEntryWeek2nd)
            barEntriesWeek3rd.add(barEntryWeek3rd)
            barEntriesWeek4th.add(barEntryWeek4th)
            val name = monthTime.MonthName
            xLabels.add(name)
        }
        bc_plates.apply {
            val barDataSetMonth = BarDataSet(barEntriesMonth, "month")
            barDataSetMonth.isHighlightEnabled = false
            barDataSetMonth.color = Color.parseColor("#ffd234")
            val barDataSetWeek1st = BarDataSet(barEntriesWeek1st, "week")
            barDataSetWeek1st.isHighlightEnabled = false
            barDataSetWeek1st.color = Color.parseColor("#2dbcff")
            val barDataSetWeek2nd = BarDataSet(barEntriesWeek2nd, "week")
            barDataSetWeek2nd.color = Color.parseColor("#2dbcff")
            val barDataSetWeek3rd = BarDataSet(barEntriesWeek3rd, "week")
            barDataSetWeek3rd.isHighlightEnabled = false
            barDataSetWeek3rd.color = Color.parseColor("#2dbcff")
            val barDataSetWeek4th = BarDataSet(barEntriesWeek4th, "week")
            barDataSetWeek4th.isHighlightEnabled = false
            barDataSetWeek4th.color = Color.parseColor("#2dbcff")
            val barData = BarData(barDataSetMonth, barDataSetWeek1st, barDataSetWeek2nd,
                    barDataSetWeek3rd, barDataSetWeek4th)
            barData.setDrawValues(false) //是否显示柱子的数值
            barData.barWidth = barWidth  //每个柱子的宽度
            this.data = barData
            axisLeft.apply {
                isEnabled = true
                setDrawGridLines(true)
                setDrawAxisLine(true)
                setDrawLabels(true)
                spaceBottom = 0f
//                axisMinimum = 0f
            }
            axisRight.isEnabled = false
            //关闭图例
            legend.isEnabled = false
            //关闭描述信息的显示
            description.isEnabled = false
            setPinchZoom(false)
            setScaleEnabled(false)
            //设置x轴显示在下方
            val markerView = MyMarkView(requireContext(), R.layout.item_achievement_markview)
            markerView.chartView = this
            marker = markerView
            xAxis.apply {
                axisMinimum = 0f
                axisMaximum = data.size.toFloat()
                position = XAxis.XAxisPosition.BOTTOM
                isGranularityEnabled = true
                labelCount = xLabels.size
                setCenterAxisLabels(true)
                setDrawAxisLine(false)
                setDrawGridLines(false)
                //设置X轴文本大小
                textSize = 10f
                textColor = Color.parseColor("#999999")
                valueFormatter = IndexAxisValueFormatter(xLabels) //设置x轴标签格式化器
                extraBottomOffset=10f
            }
            groupBars(0f, groupSpace, barSpace)
            animateXY(1000, 1000)
        }

    }

    inner class MyMarkView(context: Context, layoutResource: Int) :
            MarkerView(context, layoutResource) {
        @SuppressLint("SetTextI18n")
        override fun refreshContent(e: Entry?, highlight: Highlight?) {
            val position = e!!.x.toInt()
            tv_hint.text = "总量：${barEntriesMonth[position].y.toInt()}\n" +
                    "第一周：${barEntriesWeek1st[position].y.toInt()}\n" +
                    "第二周：${barEntriesWeek2nd[position].y.toInt()}\n" +
                    "第三周：${barEntriesWeek3rd[position].y.toInt()}\n" +
                    "第四周：${barEntriesWeek4th[position].y.toInt()}"
            super.refreshContent(e, highlight)
        }
    }
}